package com.shhm.exception;

import com.alibaba.fastjson2.JSON;
import com.shhm.common.constants.HttpStatus;
import com.shhm.common.dto.response.AjaxResultPlus;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @author JackZ
 * @version 1.0
 * @description: 未认证时处理错误
 * @date 2025/7/26 下午1:02
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED);
        response.setCharacterEncoding("utf-8");
        AjaxResultPlus rdata = AjaxResultPlus.custom(HttpStatus.UNAUTHORIZED,true)
                .put("msg", "身份认证失败！")
                .put("timestamp", new Date())
                .put("path", request.getRequestURI())
                .put("data",authException.getMessage());
        response.getWriter().write(JSON.toJSONString(rdata));
    }
}
